<template>
  <div class="analytics-container">
    <div class="page-header">
      <h1>数据统计与分析</h1>
      <div class="date-range-selector">
        <select v-model="selectedDateRange" @change="updateAnalytics">
          <option value="7days">最近7天</option>
          <option value="30days">最近30天</option>
          <option value="90days">最近90天</option>
          <option value="custom">自定义范围</option>
        </select>
        <div v-if="selectedDateRange === 'custom'" class="custom-date-range">
          <input v-model="startDate" type="date" @change="updateAnalytics" />
          <span>至</span>
          <input v-model="endDate" type="date" @change="updateAnalytics" />
        </div>
      </div>
    </div>
    
    <!-- 关键指标卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon users-icon">
          <i class="fa fa-users"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">总用户数</div>
          <div class="stat-number">{{ stats.totalUsers }}</div>
          <div class="stat-change" :class="stats.newUsersChange >= 0 ? 'positive' : 'negative'">
            <i class="fa" :class="stats.newUsersChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(stats.newUsersChange) }}%
            <span class="change-label">(较上期)</span>
          </div>
        </div>
        <div class="stat-info">
          <div class="info-item">
            <span class="label">新增用户</span>
            <span class="value">{{ stats.newUsers }}</span>
          </div>
          <div class="info-item">
            <span class="label">活跃用户</span>
            <span class="value">{{ stats.activeUsers }}</span>
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon videos-icon">
          <i class="fa fa-video-camera"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">视频总数</div>
          <div class="stat-number">{{ stats.totalVideos }}</div>
          <div class="stat-change" :class="stats.newVideosChange >= 0 ? 'positive' : 'negative'">
            <i class="fa" :class="stats.newVideosChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(stats.newVideosChange) }}%
            <span class="change-label">(较上期)</span>
          </div>
        </div>
        <div class="stat-info">
          <div class="info-item">
            <span class="label">新上传</span>
            <span class="value">{{ stats.newVideos }}</span>
          </div>
          <div class="info-item">
            <span class="label">审核中</span>
            <span class="value">{{ stats.pendingVideos }}</span>
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon views-icon">
          <i class="fa fa-eye"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">总观看量</div>
          <div class="stat-number">{{ formatNumber(stats.totalViews) }}</div>
          <div class="stat-change" :class="stats.viewsChange >= 0 ? 'positive' : 'negative'">
            <i class="fa" :class="stats.viewsChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(stats.viewsChange) }}%
            <span class="change-label">(较上期)</span>
          </div>
        </div>
        <div class="stat-info">
          <div class="info-item">
            <span class="label">日均观看</span>
            <span class="value">{{ formatNumber(stats.dailyViews) }}</span>
          </div>
          <div class="info-item">
            <span class="label">独立访客</span>
            <span class="value">{{ formatNumber(stats.uniqueVisitors) }}</span>
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon engagement-icon">
          <i class="fa fa-heart"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">互动总数</div>
          <div class="stat-number">{{ formatNumber(stats.totalEngagement) }}</div>
          <div class="stat-change" :class="stats.engagementChange >= 0 ? 'positive' : 'negative'">
            <i class="fa" :class="stats.engagementChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
            {{ Math.abs(stats.engagementChange) }}%
            <span class="change-label">(较上期)</span>
          </div>
        </div>
        <div class="stat-info">
          <div class="info-item">
            <span class="label">点赞数</span>
            <span class="value">{{ formatNumber(stats.likes) }}</span>
          </div>
          <div class="info-item">
            <span class="label">评论数</span>
            <span class="value">{{ formatNumber(stats.comments) }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 用户增长趋势 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>用户增长趋势</h3>
          <div class="chart-controls">
            <button 
              v-for="view in userGrowthViews" 
              :key="view.id"
              :class="['chart-view-btn', { active: activeUserGrowthView === view.id }]"
              @click="activeUserGrowthView = view.id"
            >
              {{ view.name }}
            </button>
          </div>
        </div>
        <div class="chart-content">
          <canvas ref="userGrowthChart" height="250"></canvas>
        </div>
      </div>
      
      <!-- 视频观看统计 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>视频观看统计</h3>
          <div class="chart-controls">
            <button 
              v-for="view in viewsStatsViews" 
              :key="view.id"
              :class="['chart-view-btn', { active: activeViewsStatsView === view.id }]"
              @click="activeViewsStatsView = view.id"
            >
              {{ view.name }}
            </button>
          </div>
        </div>
        <div class="chart-content">
          <canvas ref="viewsStatsChart" height="250"></canvas>
        </div>
      </div>
      
      <!-- 内容分类分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>内容分类分布</h3>
          <div class="chart-controls">
            <button 
              v-for="view in contentDistributionViews" 
              :key="view.id"
              :class="['chart-view-btn', { active: activeContentDistributionView === view.id }]"
              @click="activeContentDistributionView = view.id"
            >
              {{ view.name }}
            </button>
          </div>
        </div>
        <div class="chart-content">
          <canvas ref="contentDistributionChart" height="300"></canvas>
        </div>
      </div>
      
      <!-- 平台活跃度 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>平台活跃度</h3>
          <div class="chart-controls">
            <button 
              v-for="view in activityViews" 
              :key="view.id"
              :class="['chart-view-btn', { active: activeActivityView === view.id }]"
              @click="activeActivityView = view.id"
            >
              {{ view.name }}
            </button>
          </div>
        </div>
        <div class="chart-content">
          <canvas ref="activityChart" height="300"></canvas>
        </div>
      </div>
    </div>
    
    <!-- 热门内容表格 -->
    <div class="hot-content-section">
      <div class="section-header">
        <h3>热门内容排行</h3>
        <div class="hot-content-tabs">
          <button 
            v-for="tab in hotContentTabs" 
            :key="tab.id"
            :class="['tab-button', { active: activeHotContentTab === tab.id }]"
            @click="activeHotContentTab = tab.id"
          >
            {{ tab.name }}
          </button>
        </div>
      </div>
      
      <div class="hot-content-table-container">
        <table class="hot-content-table">
          <thead>
            <tr>
              <th>排名</th>
              <th>封面</th>
              <th>标题</th>
              <th>作者</th>
              <th v-if="activeHotContentTab === 'views'">观看量</th>
              <th v-else-if="activeHotContentTab === 'likes'">点赞数</th>
              <th v-else-if="activeHotContentTab === 'comments'">评论数</th>
              <th v-else-if="activeHotContentTab === 'growth'">增长速度</th>
              <th>分类</th>
              <th>发布时间</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(content, index) in hotContentList" 
              :key="content.id"
              class="content-row"
            >
              <td class="rank-cell">{{ index + 1 }}</td>
              <td class="cover-cell">
                <img :src="content.cover" :alt="content.title" />
              </td>
              <td class="title-cell">{{ content.title }}</td>
              <td class="author-cell">
                <div class="author-info">
                  <div class="author-avatar" :style="{ backgroundColor: getAvatarColor(content.author) }">{{ getInitial(content.author) }}</div>
                  <span class="author-name">{{ content.author }}</span>
                </div>
              </td>
              <td class="metric-cell">
                <div class="metric-value">
                  {{ formatNumber(content.metricValue) }}
                </div>
                <div class="metric-change" :class="content.metricChange >= 0 ? 'positive' : 'negative'">
                  <i class="fa" :class="content.metricChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down'"></i>
                  {{ Math.abs(content.metricChange) }}%
                </div>
              </td>
              <td class="category-cell">
                <span class="category-badge">{{ content.category }}</span>
              </td>
              <td class="date-cell">{{ formatDate(content.publishDate) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
// 导入 Chart.js 核心和需要的组件
import { Chart, registerables } from 'chart.js'
// 注册所有组件
Chart.register(...registerables)

export default {
  name: 'AnalyticsView',
  data() {
    return {
      // 日期范围选择
      selectedDateRange: '30days',
      startDate: '',
      endDate: '',
      
      // 图表引用
      userGrowthChart: null,
      viewsStatsChart: null,
      contentDistributionChart: null,
      activityChart: null,
      
      // 图表视图切换
      activeUserGrowthView: 'newUsers',
      activeViewsStatsView: 'dailyViews',
      activeContentDistributionView: 'videos',
      activeActivityView: 'timeOfDay',
      activeHotContentTab: 'views',
      
      // 图表视图选项
      userGrowthViews: [
        { id: 'newUsers', name: '新增用户' },
        { id: 'activeUsers', name: '活跃用户' },
        { id: 'retention', name: '用户留存' },
      ],
      viewsStatsViews: [
        { id: 'dailyViews', name: '日观看量' },
        { id: 'averageWatchTime', name: '平均观看时长' },
        { id: 'completionRate', name: '完成率' },
      ],
      contentDistributionViews: [
        { id: 'videos', name: '视频数' },
        { id: 'views', name: '观看量' },
        { id: 'engagement', name: '互动量' },
      ],
      activityViews: [
        { id: 'timeOfDay', name: '时段分布' },
        { id: 'dayOfWeek', name: '星期分布' },
        { id: 'device', name: '设备分布' },
      ],
      hotContentTabs: [
        { id: 'views', name: '观看量' },
        { id: 'likes', name: '点赞数' },
        { id: 'comments', name: '评论数' },
        { id: 'growth', name: '增长速度' },
      ],
      
      // 统计数据（模拟数据）
      stats: {
        totalUsers: 12560,
        newUsers: 845,
        activeUsers: 3420,
        newUsersChange: 12.5,
        totalVideos: 5890,
        newVideos: 234,
        pendingVideos: 45,
        newVideosChange: 8.3,
        totalViews: 1567890,
        dailyViews: 52263,
        uniqueVisitors: 28945,
        viewsChange: 15.2,
        totalEngagement: 456789,
        likes: 345678,
        comments: 111111,
        engagementChange: 10.8,
      },
      
      // 图表数据（模拟数据）
      chartData: {
        dates: Array.from({ length: 30 }, (_, i) => {
          const date = new Date()
          date.setDate(date.getDate() - 29 + i)
          return date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })
        }),
        newUsers: Array.from({ length: 30 }, () => Math.floor(Math.random() * 50) + 20),
        activeUsers: Array.from({ length: 30 }, () => Math.floor(Math.random() * 150) + 80),
        dailyViews: Array.from({ length: 30 }, () => Math.floor(Math.random() * 10000) + 30000),
        averageWatchTime: Array.from({ length: 30 }, () => Math.floor(Math.random() * 300) + 600),
        categories: ['游戏', '娱乐', '科技', '教育', '音乐', '电影', '生活', '体育', '其他'],
        categoryVideos: [1240, 980, 870, 760, 650, 540, 430, 320, 200],
        categoryViews: [345000, 289000, 234000, 198000, 176000, 154000, 132000, 111000, 89000],
        timeOfDay: Array.from({ length: 24 }, (_, i) => i),
        hourlyActivity: [1200, 800, 600, 400, 300, 500, 1500, 3500, 5500, 6500, 7500, 8500, 8200, 8800, 9500, 10500, 12500, 13500, 11500, 9500, 7500, 5500, 3500, 2000],
        devices: ['移动端', '桌面端', '平板端', '其他'],
        deviceDistribution: [65, 25, 8, 2],
      },
      
      // 热门内容数据（模拟数据）
      hotContentData: {
        views: [
          { id: 'v001', title: '《王者荣耀》新版本英雄解析', author: '游戏达人', cover: 'https://picsum.photos/id/11/160/90', category: '游戏', metricValue: 125432, metricChange: 25.8, publishDate: '2024-05-10T08:00:00Z' },
          { id: 'v002', title: '2024年最新科技产品评测', author: '科技先锋', cover: 'https://picsum.photos/id/20/160/90', category: '科技', metricValue: 98765, metricChange: 18.5, publishDate: '2024-05-12T10:30:00Z' },
          { id: 'v003', title: '流行歌曲翻唱合集', author: '音乐小天后', cover: 'https://picsum.photos/id/24/160/90', category: '音乐', metricValue: 87654, metricChange: 32.1, publishDate: '2024-05-09T14:20:00Z' },
          { id: 'v004', title: '一分钟学会家常菜谱', author: '美食达人', cover: 'https://picsum.photos/id/292/160/90', category: '生活', metricValue: 76543, metricChange: 15.7, publishDate: '2024-05-11T18:00:00Z' },
          { id: 'v005', title: '最新电影深度解析', author: '影评人', cover: 'https://picsum.photos/id/96/160/90', category: '电影', metricValue: 65432, metricChange: 10.2, publishDate: '2024-05-13T09:15:00Z' },
        ],
        likes: [
          { id: 'v003', title: '流行歌曲翻唱合集', author: '音乐小天后', cover: 'https://picsum.photos/id/24/160/90', category: '音乐', metricValue: 28965, metricChange: 35.4, publishDate: '2024-05-09T14:20:00Z' },
          { id: 'v001', title: '《王者荣耀》新版本英雄解析', author: '游戏达人', cover: 'https://picsum.photos/id/11/160/90', category: '游戏', metricValue: 25678, metricChange: 22.1, publishDate: '2024-05-10T08:00:00Z' },
          { id: 'v004', title: '一分钟学会家常菜谱', author: '美食达人', cover: 'https://picsum.photos/id/292/160/90', category: '生活', metricValue: 19876, metricChange: 18.9, publishDate: '2024-05-11T18:00:00Z' },
          { id: 'v006', title: '健身达人的日常训练', author: '健身教练', cover: 'https://picsum.photos/id/176/160/90', category: '体育', metricValue: 15678, metricChange: 42.3, publishDate: '2024-05-14T07:30:00Z' },
          { id: 'v002', title: '2024年最新科技产品评测', author: '科技先锋', cover: 'https://picsum.photos/id/20/160/90', category: '科技', metricValue: 12345, metricChange: 15.6, publishDate: '2024-05-12T10:30:00Z' },
        ],
        comments: [
          { id: 'v001', title: '《王者荣耀》新版本英雄解析', author: '游戏达人', cover: 'https://picsum.photos/id/11/160/90', category: '游戏', metricValue: 5678, metricChange: 30.2, publishDate: '2024-05-10T08:00:00Z' },
          { id: 'v005', title: '最新电影深度解析', author: '影评人', cover: 'https://picsum.photos/id/96/160/90', category: '电影', metricValue: 4321, metricChange: 28.7, publishDate: '2024-05-13T09:15:00Z' },
          { id: 'v002', title: '2024年最新科技产品评测', author: '科技先锋', cover: 'https://picsum.photos/id/20/160/90', category: '科技', metricValue: 3890, metricChange: 22.4, publishDate: '2024-05-12T10:30:00Z' },
          { id: 'v007', title: '教育改革新政策解读', author: '教育专家', cover: 'https://picsum.photos/id/366/160/90', category: '教育', metricValue: 3456, metricChange: 45.1, publishDate: '2024-05-15T11:00:00Z' },
          { id: 'v003', title: '流行歌曲翻唱合集', author: '音乐小天后', cover: 'https://picsum.photos/id/24/160/90', category: '音乐', metricValue: 2987, metricChange: 18.5, publishDate: '2024-05-09T14:20:00Z' },
        ],
        growth: [
          { id: 'v008', title: '突发新闻事件现场报道', author: '新闻记者', cover: 'https://picsum.photos/id/239/160/90', category: '娱乐', metricValue: 89000, metricChange: 125.8, publishDate: '2024-05-16T09:45:00Z' },
          { id: 'v006', title: '健身达人的日常训练', author: '健身教练', cover: 'https://picsum.photos/id/176/160/90', category: '体育', metricValue: 45600, metricChange: 78.3, publishDate: '2024-05-14T07:30:00Z' },
          { id: 'v007', title: '教育改革新政策解读', author: '教育专家', cover: 'https://picsum.photos/id/366/160/90', category: '教育', metricValue: 32100, metricChange: 65.4, publishDate: '2024-05-15T11:00:00Z' },
          { id: 'v009', title: '网络热门话题讨论', author: '评论员', cover: 'https://picsum.photos/id/325/160/90', category: '娱乐', metricValue: 28900, metricChange: 55.7, publishDate: '2024-05-16T13:20:00Z' },
          { id: 'v010', title: '罕见动物行为记录', author: '自然爱好者', cover: 'https://picsum.photos/id/237/160/90', category: '生活', metricValue: 25600, metricChange: 48.9, publishDate: '2024-05-14T16:10:00Z' },
        ],
      },
    }
  },
  computed: {
    hotContentList() {
      return this.hotContentData[this.activeHotContentTab] || []
    },
  },
  mounted() {
    // 设置默认日期范围
    const today = new Date()
    const lastMonth = new Date()
    lastMonth.setMonth(lastMonth.getMonth() - 1)
    
    this.endDate = today.toISOString().split('T')[0]
    this.startDate = lastMonth.toISOString().split('T')[0]
    
    // 在DOM加载完成后初始化图表
    this.$nextTick(() => {
      this.initCharts()
      
      // 监听视图切换
      this.$watch('activeUserGrowthView', () => this.updateUserGrowthChart())
      this.$watch('activeViewsStatsView', () => this.updateViewsStatsChart())
      this.$watch('activeContentDistributionView', () => this.updateContentDistributionChart())
      this.$watch('activeActivityView', () => this.updateActivityChart())
    })
  },
  beforeUnmount() {
    // 销毁图表实例，避免内存泄漏
    this.destroyCharts()
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      this.initUserGrowthChart()
      this.initViewsStatsChart()
      this.initContentDistributionChart()
      this.initActivityChart()
    },
    
    // 销毁所有图表
    destroyCharts() {
      if (this.userGrowthChart) {
        this.userGrowthChart.destroy()
      }
      if (this.viewsStatsChart) {
        this.viewsStatsChart.destroy()
      }
      if (this.contentDistributionChart) {
        this.contentDistributionChart.destroy()
      }
      if (this.activityChart) {
        this.activityChart.destroy()
      }
    },
    
    // 用户增长趋势图表
    initUserGrowthChart() {
      if (!this.$refs.userGrowthChart) {
        console.warn('userGrowthChart引用未找到，跳过图表初始化')
        return
      }
      const ctx = this.$refs.userGrowthChart.getContext('2d')
      this.userGrowthChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.chartData.dates,
          datasets: [{
            label: '新增用户',
            data: this.chartData.newUsers,
            borderColor: '#3498db',
            backgroundColor: 'rgba(52, 152, 219, 0.1)',
            tension: 0.3,
            fill: true,
          }],
        },
        options: this.getChartOptions('新增用户数'),
      })
    },
    
    updateUserGrowthChart() {
      if (!this.userGrowthChart) return
      
      let data, label, color
      
      switch (this.activeUserGrowthView) {
        case 'activeUsers':
          data = this.chartData.activeUsers
          label = '活跃用户'
          color = '#2ecc71'
          break
        case 'retention':
          // 计算留存率（模拟数据）
          data = this.chartData.activeUsers.map((active, i) => {
            const newUsers = this.chartData.newUsers[i]
            return newUsers > 0 ? Math.round((active / newUsers) * 100) : 0
          })
          label = '用户留存率'
          color = '#9b59b6'
          break
        default:
          data = this.chartData.newUsers
          label = '新增用户'
          color = '#3498db'
      }
      
      this.userGrowthChart.data.datasets[0] = {
        label,
        data,
        borderColor: color,
        backgroundColor: `${color}20`,
        tension: 0.3,
        fill: true,
      }
      
      this.userGrowthChart.options.scales.y.title.text = this.activeUserGrowthView === 'retention' ? '留存率 (%)' : '用户数'
      this.userGrowthChart.update()
    },
    
    // 视频观看统计图表
    initViewsStatsChart() {
      if (!this.$refs.viewsStatsChart) {
        console.warn('viewsStatsChart引用未找到，跳过图表初始化')
        return
      }
      const ctx = this.$refs.viewsStatsChart.getContext('2d')
      this.viewsStatsChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: this.chartData.dates,
          datasets: [{
            label: '日观看量',
            data: this.chartData.dailyViews,
            backgroundColor: '#e74c3c',
            borderRadius: 4,
          }],
        },
        options: this.getChartOptions('观看量'),
      })
    },
    
    updateViewsStatsChart() {
      if (!this.viewsStatsChart) return
      
      let data, label, color, type
      
      switch (this.activeViewsStatsView) {
        case 'averageWatchTime':
          data = this.chartData.averageWatchTime
          label = '平均观看时长（秒）'
          color = '#f39c12'
          type = 'line'
          break
        case 'completionRate':
          // 计算完成率（模拟数据）
          data = this.chartData.dailyViews.map(() => Math.floor(Math.random() * 40) + 40)
          label = '完成率 (%)'
          color = '#1abc9c'
          type = 'line'
          break
        default:
          data = this.chartData.dailyViews
          label = '日观看量'
          color = '#e74c3c'
          type = 'bar'
      }
      
      this.viewsStatsChart.config.type = type
      this.viewsStatsChart.data.datasets[0] = {
        label,
        data,
        backgroundColor: type === 'bar' ? color : 'transparent',
        borderColor: type === 'line' ? color : 'transparent',
        backgroundColor: type === 'line' ? `${color}20` : color,
        tension: type === 'line' ? 0.3 : 0,
        fill: type === 'line',
        borderRadius: type === 'bar' ? 4 : 0,
      }
      
      this.viewsStatsChart.update()
    },
    
    // 内容分类分布图表
    initContentDistributionChart() {
      if (!this.$refs.contentDistributionChart) {
        console.warn('contentDistributionChart引用未找到，跳过图表初始化')
        return
      }
      const ctx = this.$refs.contentDistributionChart.getContext('2d')
      this.contentDistributionChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: this.chartData.categories,
          datasets: [{
            data: this.chartData.categoryVideos,
            backgroundColor: this.getChartColors(this.chartData.categories.length),
          }],
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'right',
              labels: {
                padding: 20,
                font: {
                  size: 12,
                },
              },
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const label = context.label || ''
                  const value = context.parsed || 0
                  const total = context.dataset.data.reduce((a, b) => a + b, 0)
                  const percentage = Math.round((value / total) * 100)
                  return `${label}: ${value} (${percentage}%)`
                },
              },
            },
          },
          cutout: '60%',
        },
      })
    },
    
    updateContentDistributionChart() {
      if (!this.contentDistributionChart) return
      
      let data, label
      
      switch (this.activeContentDistributionView) {
        case 'views':
          data = this.chartData.categoryViews
          break
        case 'engagement':
          // 模拟互动数据
          data = this.chartData.categoryVideos.map(videos => videos * Math.floor(Math.random() * 50) + 20)
          break
        default:
          data = this.chartData.categoryVideos
      }
      
      this.contentDistributionChart.data.datasets[0].data = data
      this.contentDistributionChart.update()
    },
    
    // 平台活跃度图表
    initActivityChart() {
      if (!this.$refs.activityChart) {
        console.warn('activityChart引用未找到，跳过图表初始化')
        return
      }
      const ctx = this.$refs.activityChart.getContext('2d')
      this.activityChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.chartData.timeOfDay.map(hour => `${hour}:00`),
          datasets: [{
            label: '活跃用户数',
            data: this.chartData.hourlyActivity,
            borderColor: '#9b59b6',
            backgroundColor: 'rgba(155, 89, 182, 0.1)',
            tension: 0.4,
            fill: true,
          }],
        },
        options: this.getChartOptions('活跃用户数'),
      })
    },
    
    updateActivityChart() {
      if (!this.activityChart) return
      
      let labels, data, label, type, color
      
      switch (this.activeActivityView) {
        case 'dayOfWeek':
          labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          data = [6500, 7200, 7800, 8200, 9500, 12500, 13200]
          label = '活跃用户数'
          type = 'bar'
          color = '#e67e22'
          break
        case 'device':
          labels = this.chartData.devices
          data = this.chartData.deviceDistribution
          label = '用户占比 (%)'
          type = 'pie'
          color = this.getChartColors(labels.length)
          break
        default:
          labels = this.chartData.timeOfDay.map(hour => `${hour}:00`)
          data = this.chartData.hourlyActivity
          label = '活跃用户数'
          type = 'line'
          color = '#9b59b6'
      }
      
      this.activityChart.config.type = type
      this.activityChart.data.labels = labels
      
      if (type === 'pie') {
        this.activityChart.data.datasets[0] = {
          label,
          data,
          backgroundColor: color,
        }
        this.activityChart.options.plugins.legend.position = 'right'
        this.activityChart.options.scales = {}
      } else {
        this.activityChart.data.datasets[0] = {
          label,
          data,
          borderColor: type === 'line' ? color : 'transparent',
          backgroundColor: type === 'bar' ? color : `${color}20`,
          tension: type === 'line' ? 0.4 : 0,
          fill: type === 'line',
          borderRadius: type === 'bar' ? 4 : 0,
        }
        this.activityChart.options.plugins.legend.position = 'top'
        this.activityChart.options.scales = this.getDefaultScales(label.includes('%') ? ' (%)' : '')
      }
      
      this.activityChart.update()
    },
    
    // 图表通用选项
    getChartOptions(yLabel) {
      return {
        responsive: true,
        plugins: {
          legend: {
            position: 'top',
            labels: {
              usePointStyle: true,
            },
          },
          tooltip: {
            mode: 'index',
            intersect: false,
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            titleFont: {
              size: 14,
            },
            bodyFont: {
              size: 13,
            },
            padding: 12,
            cornerRadius: 6,
          },
        },
        scales: this.getDefaultScales(yLabel),
      }
    },
    
    getDefaultScales(yLabel) {
      return {
        x: {
          grid: {
            display: false,
          },
        },
        y: {
          beginAtZero: true,
          grid: {
            borderDash: [3, 3],
          },
          title: {
            display: true,
            text: yLabel,
          },
        },
      }
    },
    
    // 获取图表颜色
    getChartColors(count) {
      const baseColors = [
        '#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6',
        '#1abc9c', '#e67e22', '#34495e', '#95a5a6', '#f1c40f',
      ]
      
      const colors = []
      for (let i = 0; i < count; i++) {
        colors.push(baseColors[i % baseColors.length])
      }
      return colors
    },
    
    // 更新分析数据
    updateAnalytics() {
      // 在实际应用中，这里应该调用API获取对应日期范围的数据
      // 这里我们只是简单地模拟刷新图表
      this.destroyCharts()
      this.initCharts()
    },
    
    // 格式化数字（添加千位分隔符）
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    },
    
    // 获取头像颜色
    getAvatarColor(name) {
      const colors = ['#3498db', '#e74c3c', '#2ecc71', '#9b59b6', '#f39c12', '#1abc9c']
      let hash = 0
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash)
      }
      return colors[Math.abs(hash) % colors.length]
    },
    
    // 获取用户名首字母
    getInitial(name) {
      return name.charAt(0).toUpperCase()
    },
  },
}
</script>

<style scoped>
.analytics-container {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
  font-size: 24px;
}

.date-range-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-range-selector select {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.custom-date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.custom-date-range input {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0,0,0,0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  color: white;
  margin-bottom: 15px;
}

.users-icon {
  background: #3498db;
}

.videos-icon {
  background: #e74c3c;
}

.views-icon {
  background: #2ecc71;
}

.engagement-icon {
  background: #f39c12;
}

.stat-content {
  margin-bottom: 15px;
}

.stat-title {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-change {
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-change.positive {
  color: #2ecc71;
}

.stat-change.negative {
  color: #e74c3c;
}

.change-label {
  font-size: 12px;
  color: #95a5a6;
  font-weight: normal;
}

.stat-info {
  display: flex;
  justify-content: space-between;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.info-item .label {
  font-size: 12px;
  color: #95a5a6;
}

.info-item .value {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

/* 图表区域 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.chart-controls {
  display: flex;
  gap: 5px;
}

.chart-view-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.3s;
}

.chart-view-btn:hover {
  background: #f8f9fa;
}

.chart-view-btn.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.chart-content {
  position: relative;
}

/* 热门内容区域 */
.hot-content-section {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.hot-content-tabs {
  display: flex;
  gap: 0;
  background: #f8f9fa;
  border-radius: 6px;
  padding: 4px;
}

.tab-button {
  padding: 8px 16px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #7f8c8d;
  transition: all 0.3s;
}

.tab-button:hover {
  color: #3498db;
}

.tab-button.active {
  background: white;
  color: #3498db;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* 热门内容表格 */
.hot-content-table-container {
  overflow-x: auto;
}

.hot-content-table {
  width: 100%;
  border-collapse: collapse;
}

.hot-content-table th,
.hot-content-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.hot-content-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
  white-space: nowrap;
}

.content-row:hover {
  background: #f8f9fa;
}

.rank-cell {
  font-weight: 600;
  color: #3498db;
  width: 60px;
}

.cover-cell {
  width: 80px;
}

.cover-cell img {
  width: 80px;
  height: 45px;
  object-fit: cover;
  border-radius: 4px;
}

.title-cell {
  max-width: 300px;
}

.title-cell:hover {
  color: #3498db;
  cursor: pointer;
}

.author-cell {
  width: 150px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 12px;
}

.author-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.metric-cell {
  width: 150px;
}

.metric-value {
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
}

.metric-change {
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 3px;
  margin-top: 2px;
}

.metric-change.positive {
  color: #2ecc71;
}

.metric-change.negative {
  color: #e74c3c;
}

.category-badge {
  padding: 3px 10px;
  background: #3498db;
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.date-cell {
  color: #7f8c8d;
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .date-range-selector {
    flex-direction: column;
    align-items: stretch;
  }
  
  .custom-date-range {
    justify-content: space-between;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .chart-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .hot-content-tabs {
    overflow-x: auto;
    padding: 4px 4px 4px 10px;
  }
  
  .tab-button {
    white-space: nowrap;
    min-width: 80px;
  }
  
  .hot-content-table {
    font-size: 14px;
  }
  
  .hot-content-table th,
  .hot-content-table td {
    padding: 8px;
  }
  
  .cover-cell img {
    width: 60px;
    height: 34px;
  }
  
  .title-cell {
    max-width: 200px;
  }
}

@media (max-width: 480px) {
  .stat-number {
    font-size: 24px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
  
  .metric-value {
    font-size: 16px;
  }
  
  .author-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .hot-content-table {
    font-size: 12px;
  }
  
  .hot-content-table th,
  .hot-content-table td {
    padding: 6px 4px;
  }
}
</style>